import { TabsPage } from './../tabs/tabs';
import { Component, Injector, ViewChild } from '@angular/core';
import { IonicPage, Tabs, ViewController, NavController, IonicApp,NavParams, Platform, ModalController, Loading, AlertController, MenuController, LoadingController, ToastController, App } from 'ionic-angular';
import { SERVER_URL } from "./../../providers/Config";
import { UserService } from './../../providers/UserService';
import { DataService } from './../../providers/DataService';
import { StorageService } from './../../providers/StorageService';
import { HomePage } from '../home/home';
import { BackButtonProvider } from "../../providers/back-button/back-button";
// import { BackButtonService } from '../../providers/backButton';

import { BasePage } from '../basePage';

declare var $: any;
/**
 * Generated class for the LoginPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-login',

  templateUrl: 'login.html',
})
export class LoginPage {

  backNum: any;
  userinfo: any;
  isToNail: boolean;
  callback: any;

  // @ViewChild('myTabs') tabRef: Tabs;
  /** 登陆后台参数loginVo */
  loginVo = {
    user_phone: '',
    user_pwd: '',
    captcha: '',
    guid: ''
  }
  /** 验证码图片地址 */
  picUrl = '';//AppConst.SERVER_URL + 'generateCaptcha?' + new Date().getTime();
  screenHeight: any;
  marginTop: any;

  /*定义一个变量保存是否是从订单页面跳转而来*/
  fromOrderMsg: Boolean;




  //控制硬件返回按钮是否触发，默认false
  backButtonPressed: boolean = false;
  backButtonToRoot: boolean = false;
  // constructor(public navCtrl: NavController, public alertCtrl: AlertController,public navParams: NavParams) {
  // }
  constructor(injector: Injector,
    public navCtrl: NavController,
    public platform: Platform,
    public alertCtrl: AlertController,
    public viewCtrl: ViewController,
    public modalCtrl: ModalController,
    public toastCtrl: ToastController,
    public loadingCtrl: LoadingController,
    public stc: StorageService,
    public userService: UserService,
    public ionicApp:IonicApp,
    public params: NavParams,
    public backButtonService: BackButtonProvider,
    public appCtrl: App) {
    this.loginVo.user_phone = this.stc.read<string>('phone') == null ? '' : this.stc.read<string>('phone');
    //this.loginVo.user_pwd = this.stc.read<string>('type') == null ? '' : this.stc.read<string>('password');
    //防止浏览器点刷新按钮后，不回退到登陆
    this.userinfo = this.stc.read('userinfo')
    platform.ready().then(() => {
      // this.registerBackButtonAction(null);
    });
    this.callback = this.params.get("callback");
    this.platform.ready().then(() => {
      // this.backButtonService.registerBackButtonAction(null,this.backButtonToRoot());
      this.backButtonService.registerBackButtonAction(null,this.navCtrl,this.ionicApp);
  });

  }

  ionViewDidLoad() {

    console.log('ionViewDidLoad LoginPage');
    this.screenHeight = screen.height;
    let num = this.screenHeight;
    this.marginTop = parseInt(num) * 0.4 + 'px';
    console.log(this.screenHeight + '和' + this.marginTop);
    this.screenHeight = parseInt(num) + 'px';

    /*接收navCtrl.push() 传过来的数据*/
    console.log(this.params.get('goods_id'))
    if (this.params.get('goods_id') != null) {
      this.fromOrderMsg = true;
      console.log('从order页面跳转而来');
    }

  }
  backButtonToRootFn(){
    // this.navCtrl.setRoot(TabsPage)
    if (this.backButtonToRoot) {
      this.navCtrl.setRoot(TabsPage)
    } else {
      this.backButtonToRoot = true;
      //两秒后标记为false，如果退出的话，就不会执行了
      setTimeout(() => this.backButtonToRoot = false, 1000);
    }
  }

  /**每次都加载 对返回的数据进行处理 */
  ionViewWillEnter() {
    // this.backNum=20;
    // this.unRegisterBack();
    //得到验证码
    // this.changeVerifyCode();
  }
  loginRefuresher() {
    console.log("执行刷新了")
    // this.cd.detectChanges();
    // window.history.go(0)
    // window.location.reload()
  }

  ionViewDidLeave() {
    console.log("5.0 ionViewDidLeave 离开页面时触发");
    
    // this.backNum=1;
    // this.unRegisterBack();
    // console.log(this.backNum);
    // if(this.userinfo==null){
    //   console.log("userinfo是空的");
    // this.navCtrl.setRoot(TabsPage) ;
    // this.viewCtrl.dismissAll();
    // }


  }

  /**跳转到找回密码 */
  doFindPwd() {
    this.navCtrl.push("FindpwdPage");
  }
  // unRegisterBack() {
  //   this.platform.registerBackButtonAction(() => {
  //     this.navCtrl.setRoot(TabsPage);
  //     this.backNum=1;
  //     return false;
  //   }, this.backNum);
  // }
  /** 跳转到注册 */
  doRegister() {
    this.navCtrl.push("RegisterPage");
  }



  /** 刷新验证码 */
  // async changeVerifyCode() {
  //   $.ajax({
  //     url: SERVER_URL + 'generateCaptcha',
  //     type: "GET",
  //     dataType: "jsonp", //指定服务器返回的数据类型
  //     jsonp: "jsonpCallback",
  //     success: (retult) => {
  //       let vcodeObj = JSON.stringify(retult.data); //json对象转成字符串
  //       let res = JSON.parse(vcodeObj);
  //       this.picUrl = res['captcha'];
  //       this.loginVo.guid = res['guid'];
  //     }
  //   });

  // }



  /** 登陆 */
  async doLogin() {
    let re =  /^1[3|4|5|6|7|8|9]\d{9}$/
    var pswre =  /^([a-zA-Z0-9]|[!.@#$%^&*]){6,12}$/;
    if(this.loginVo.user_phone == ''){
      this.showAlert('', '手机号不能为空')
      // this.changeVerifyCode();
      return;
    }
    if (!re.test(this.loginVo.user_phone)) {
      this.showAlert('', '手机号不正确')
      // this.changeVerifyCode();
      return;
    }
    if (this.loginVo.user_pwd.trim().length == 0) {
      this.showAlert('', '密码不能为空');
      // this.changeVerifyCode();
      return;
    }
    if (!pswre.test(this.loginVo.user_pwd.trim())) {
      this.showAlert('', '密码必须要在6~12位之间');
      // this.changeVerifyCode();
      return;
    }
    //.......
    let loader = this.loadingCtrl.create({
      content: "",
    });
    loader.present();

    console.log(this.loginVo);

    //请求后台登陆
    let result = await this.userService.doLoginAPI(this.loginVo);
    loader.dismiss();
    console.log(result);
    if (result.code != 1) {
      this.showAlert('', result.msg);
      // this.changeVerifyCode();
      return;
    }

    //将正确的手机号及身份记入cookie
    // this.stc.write('phone', this.loginVo.user_phone);
    // this.stc.write('password', this.loginVo.user_pwd);
    //将后台返回的用户数据保存到内存,方便其他模块去取
    result.data['user_phone'] = this.loginVo.user_phone;
    result.data['user_pwd'] = this.loginVo.user_pwd;
    this.stc.write('userinfo', result.data);
    this.stc.write('selectIndex', 4);
    // this.navCtrl.setRoot('personal');
    this.navCtrl.setRoot(TabsPage);
    console.log(this.params.data)
    // if(this.params.data == null){
    //   /*如果不是从订单确认页面跳转而来，直接跳转到首页*/
    //   this.navCtrl.setRoot(TabsPage);
    // }else{
    //   /*如果跳转到登录页面的时候携带了参数 就继续跳转到原来的页面*/

    //   this.navCtrl.pop(this.orderMsg);

    // }
    // if(this.params.data.reload == true){
    //   /*如果不是从订单确认页面跳转而来，直接跳转到首页*/
    //   this.navCtrl.setRoot(TabsPage);
    // }else if(this.params.data!=null){
    //   /*如果跳转到登录页面的时候携带了参数 就继续跳转到原来的页面*/

    //   this.navCtrl.pop(this.orderMsg);

    // }
  }



  /** 提示 */
  showAlert(_title, _msg) {
    let alert = this.alertCtrl.create({
      title: _title,
      subTitle: _msg,
      buttons: ['确定']
    });
    alert.present();
  }

  /*监听手机返回键*/

}
